<template>
  <a-modal
    v-model:open="localVisible"
    title="分配角色"
    @ok="handleSubmit"
    @cancel="handleCancel"
    :confirm-loading="submitLoading"
  >
    <a-spin :spinning="loading">
      <a-checkbox-group 
        v-model:value="selectedRoles" 
        style="width: 100%"
      >
        <a-row>
          <a-col 
            v-for="role in roleList" 
            :key="role.id"
            :span="8"
            style="margin-bottom: 8px"
          >
            <a-checkbox :value="role.id">{{ role.name }}</a-checkbox>
          </a-col>
        </a-row>
      </a-checkbox-group>
    </a-spin>
  </a-modal>
</template>

<script setup>
import { ref, watch, computed } from 'vue';

const props = defineProps({
  visible: {
    type: Boolean,
    default: false
  },
  loading: {
    type: Boolean,
    default: false
  },
  submitLoading: {
    type: Boolean,
    default: false
  },
  roleList: {
    type: Array,
    default: () => []
  },
  userRoles: {
    type: Array,
    default: () => []
  },
  userId: {
    type: [Number, String],
    default: null
  }
});

const emit = defineEmits(['update:visible', 'submit', 'cancel']);

// 选中的角色
const selectedRoles = ref([]);

// 监听userRoles变化，更新选中的角色
watch(
  () => props.userRoles,
  (newVal) => {
    if (newVal && newVal.length) {
      selectedRoles.value = newVal.map(role => 
        typeof role === 'object' ? role.id : role
      );
    } else {
      selectedRoles.value = [];
    }
  },
  { immediate: true, deep: true }
);

// 监听visible变化，重置选中角色
watch(
  () => props.visible,
  (newVal) => {
    if (!newVal) {
      selectedRoles.value = [];
    }
  }
);

// 使用计算属性代理visible属性
const localVisible = computed({
  get: () => props.visible,
  set: (value) => emit('update:visible', value)
});

// 提交表单
const handleSubmit = () => {
  emit('submit', {
    userId: props.userId,
    roleIds: selectedRoles.value
  });
};

// 取消操作
const handleCancel = () => {
  emit('update:visible', false);
  emit('cancel');
};

// 暴露属性给父组件
defineExpose({
  selectedRoles
});
</script>

<style scoped>
</style> 